<?php
/**
 * 第4步，执行安装
 */
include_once dirname(__FILE__).'/_config.php';

$_POST['sitekey'] = empty($_POST['sitekey'])	? '' : trim($_POST['sitekey']);
$_POST['pre'] = empty($_POST['pre'])	? '' : trim($_POST['pre']);
$_POST['db_host'] = empty($_POST['db_host'])	? '' : trim($_POST['db_host']);
$_POST['db_user'] = empty($_POST['db_user'])	? '' : trim($_POST['db_user']);
$_POST['db_pass'] = empty($_POST['db_pass'])	? '' : trim($_POST['db_pass']);
$_POST['db_name'] = empty($_POST['db_name'])	? '' : trim($_POST['db_name']);
$_POST['db_pre']  = empty($_POST['db_pre'])		? '' : trim($_POST['db_pre']);

$_POST['way']     = empty($_POST['way'])		? 0 : intval($_POST['way']);
$_POST['demo']    = empty($_POST['demo'])		? 0 : 1;

$_POST['m_user']  = empty($_POST['m_user'])		? '' : trim($_POST['m_user']);
$_POST['m_pass']  = empty($_POST['m_pass'])		? '' : trim($_POST['m_pass']);
$_POST['m_pwd']   = empty($_POST['m_pwd'])		? '' : trim($_POST['m_pwd']);
$_POST['m_email'] = empty($_POST['m_email'])	? '' : trim($_POST['m_email']);

/*******************************************************************************
 * 基本数据校验
 *******************************************************************************/
$errmsg = array();
if(empty($_POST['db_host'])){$errmsg[] = ilang('dbinfo_dbhost_invalid');}
if(empty($_POST['db_user'])){$errmsg[] = ilang('dbinfo_dbuser_invalid');}
// if(empty($_POST['db_pass'])){$errmsg[] = ilang('dbinfo_dbpw_invalid');}
if(empty($_POST['db_name'])){$errmsg[] = ilang('dbinfo_dbname_invalid');}
if(empty($_POST['db_pre'])){$errmsg[] = ilang('dbinfo_tablepre_invalid');}

if(empty($_POST['m_user'])){$errmsg[] = ilang('admininfo_username_invalid');}
if(empty($_POST['m_pass'])){$errmsg[] = ilang('admininfo_password_invalid');}
if(empty($_POST['m_pwd'])){$errmsg[] = ilang('admininfo_password_invalid');}
if(empty($_POST['m_email']) || preg_match('/^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/i', $_POST['m_email']) == false){$errmsg[] = ilang('admininfo_email_invalid');}
if($_POST['m_pwd'] != $_POST['m_pass']){$errmsg[] = ilang('admininfo_password2_invalid');}

/*******************************************************************************
 * 数据库检测
 *******************************************************************************/

$dbname_not_exists = check_db($_POST['db_host'], $_POST['db_user'], $_POST['db_pass'], $_POST['db_name'], $_POST['db_pre']);
if($dbname_not_exists == 'ok'){
	/*******************************************************************************
	 * 创建数据库
	 *******************************************************************************/
	$link = @mysql_connect($_POST['db_host'], $_POST['db_user'], $_POST['db_pass']);
	if(!$link){
		$errno = mysql_errno($link);
		$error = mysql_error($link);
		if($errno == 1045){
			$errmsg[] = show_msg('database_errno_1045', $error, 0);
		}elseif($errno == 2003){
			$errmsg[] = show_msg('database_errno_2003', $error, 0);
		}else {
			$errmsg[] = show_msg('database_connect_error', $error, 0);
		}
	}else{
		if(mysql_get_server_info() > '4.1'){
			mysql_query("CREATE DATABASE IF NOT EXISTS `{$_POST['db_name']}` DEFAULT CHARACTER SET ".DBCHARSET, $link);
		}else {
			mysql_query("CREATE DATABASE IF NOT EXISTS `{$_POST['db_name']}`", $link);
		}

		if(mysql_errno()){
			$errmsg[] = show_msg('database_errno_1044', mysql_error(), 0);
		}
		mysql_close($link);
	}
}
// $errmsg[] = '错误测试';
set(get_html('setup.html'));
view();
if(!empty($errmsg)){
	showjsmessage(implode('<br />', $errmsg));
	echo <<<HTML
		<script type="text/javascript" language="javascript" charset="utf=8">
		<!--
			document.getElementById('action').innerHTML = '<input type="button" value="上一步" class="button" onclick="javascript:history.back(-1);" /><br />';
		//-->
		</script>
HTML
;
	exit;
}

/*******************************************************************************
 * 配置文件
 * ##:: 这个开头的行，都要被删除
 * ##$$ 这个开头的行，如果是正式发布，删除
 * ##&& 这个开头的行，正式时使用
 *******************************************************************************/

$__self = dirname(dirname($_SERVER ['PHP_SELF']));
$__dir  = str_replace('//', '/', str_replace('\\', '/', $__self).'/');
$config = file_get_contents(MY_PATH.'data/config.inc.default');
$config = preg_replace('/##::[\s\S]+?\n/i', '', $config);
if(IN_PUBLIC){
	$config = preg_replace('/##&&\s+/i', '', $config);
	$config = preg_replace('/##\$\$[\s\S]+?\n/i', '', $config);

}else{
	$config = preg_replace('/##&&[\s\S]+?\n/i', '', $config);
	$config = preg_replace('/##\$\$\s+/i', '', $config);
}
$config = preg_replace('/[\r\n]+\s+[\r\n]+/', "\n", $config);
##^^ 安全码
if(empty($_GET['sitekey'])){
	$_GET['sitekey'] = array();
for($i = 0; $i < 5; $i ++){
		$_GET['sitekey'][] = strtoupper(genRandomString(5));
	}
}
##^^ 前缀
if(empty($_POST['pre'])){
if($_SERVER['HTTP_HOST'] == 'localhost' || $_SERVER['HTTP_HOST'] == '127.0.0.1'){
		$_POST['pre'] = str_replace('/', '_', $__dir);
}else{
	$hostarr = explode('.', $_SERVER['HTTP_HOST']);
	array_pop($hostarr);
	if($hostarr[0] == 'www'){
		array_shift($hostarr);
	}
		$_POST['pre'] = implode('_', $hostarr);
	}
}
$replace = array(
	'charset'	=> CHARSET,
	'host'		=> "http://{$_SERVER['HTTP_HOST']}",
	'root'		=> ROOT_PATH,
	'dir'		=> $__dir,
	#
	'sitekey'	=> implode('-', $_GET['sitekey']),
	'pre'		=> $_POST['pre'],
	# 数据库配置
	'db_host'	=> $_POST['db_host'],
	'db_user'	=> $_POST['db_user'],
	'db_pass'	=> $_POST['db_pass'],
	'db_name'	=> $_POST['db_name'],
	'db_pre'	=> $_POST['db_pre'],
);
foreach($replace as $key => $val){
	$config = preg_replace("/\{@{$key}\}/i", $val, $config);
}
if(file_put_contents(ROOT_PATH.'data/config.inc.php', $config)){
	showjsmessage(ilang('config_file_save_ok'));
}
// 加载生成的配置文件
try{
	include_once ROOT_PATH.'data/config.inc.php';
}catch(Exception $e){
	showjsmessage($e->getMessage());
}

/*******************************************************************************
 * .htaccess
 *******************************************************************************/
$htaccess = file_get_contents(MY_PATH.'data/htaccess.default');
$htaccess = preg_replace('/\{@webdir\}/i', $__dir, $htaccess);
if(file_put_contents(ROOT_PATH.'.htaccess', $htaccess)){
	showjsmessage('.htaccess 文件保存成功.');
}

/*******************************************************************************
 * pub.key
 *******************************************************************************/
// copy(MY_PATH.'data/pub.key', DAT_PTH.'pub.key');

/*******************************************************************************
 * 执行查询，安装数据
 *******************************************************************************/
if($_POST['way'] != 1){
	if($dbname_not_exists == 'ok' || $_POST['way'] == 2){
		showjsmessage(ilang('install_data'));
		@include_once MY_PATH.'inc/db.class.php';
		$__mydb = new dbstuff;
		$__mydb->connect($_POST['db_host'], $_POST['db_user'], $_POST['db_pass'], $_POST['db_name'], DBCHARSET);
		## 框架基础
		$sql = file_get_contents(MY_PATH.'data/dxe_base.sql');
		$sql = str_replace("\r\n", "\n", $sql);
		runquery($sql, $_POST['db_pre']);
		## 功能结构
		$sql = file_get_contents(MY_PATH.'data/dxe_struct.sql');
		$sql = str_replace("\r\n", "\n", $sql);
		runquery($sql, $_POST['db_pre']);
		## 基础数据
		$sql = file_get_contents(MY_PATH.'data/dxe_data.sql');
		$sql = str_replace("\r\n", "\n", $sql);
		runquery($sql, $_POST['db_pre']);

		/*******************************************************************************
		 * 安装示例数据
		 *******************************************************************************/
		/*if($_POST['demo'] == 1 && file_exists(MY_PATH.'data/dxe_demo.sql')){
			showjsmessage(ilang('install_test_data'));
			$sql = file_get_contents(MY_PATH.'data/dxe_demo.sql');
			$sql = str_replace("\r\n", "\n", $sql);
			runquery($sql, $_POST['db_pre']);

			// 将示例文件移动到上传目录下
			$dfilepath = MY_PATH.'data/uploads/';
			$targetpath = UP_PTH.'uploads/';
			$dirarr = array();
			if(file_exists($dfilepath) && !file_exists($targetpath)){
				if($handle = opendir($dfilepath)){
					while(false !== ($ddir = readdir($handle))){
						if($ddir == '.' || $ddir == '..'){
							continue;
						}
						if(is_dir("{$dfilepath}{$ddir}")){
							$dirarr[] = $ddir;
						}
					}
					closedir($handle);
				}
				foreach($dirarr as $ddir){
					rename("{$dfilepath}{$ddir}", "{$targetpath}{$ddir}");
				}
			}
		}*/
		$__mydb->close();
	}
}

##^^ 模板缓存
// include_once CLS_PTH.'tools/File.class.php';
// File::cache_cls_files();	## 缓存类文件路径
// $styles = File::get_styles();
// cache_write('styles.php', $styles);


## 生成缓存
// $oMenu = new Menu();
// $cache_menu = $oMenu->cache_menu();

// $oRole = new Role();
// $cache_role = $oRole->cache_all();

// $oLang = new Lang();
// $oLang->cache_lang();

// $oLibrary = new Library();
// $oLibrary->cache_library();

// $oAdpos = new Adpos();
// $oAdpos->cache_adpos();

// $oAdvert = new Advert();
// $oAdvert->cache_advert();

$oSysVar = new SysVar();
$oSysVar->update(10, array('type' => 3, 'value' => 'php'));
$oSysVar->cache_sysvar();

/*******************************************************************************
 * 修改管理员信息
 *******************************************************************************/
$__db = new DBase(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$__db->query("TRUNCATE `{$_POST['db_pre']}manager`");
$oManager = new Manager();
$pwdmd5 = $oManager->genral_password($_POST['m_pass']);
$manager_info = array (
	'username'	=> $_POST['m_user'],
	'password'	=> $pwdmd5,
	'role'		=> '1',
	'subset'	=> 'DEFAULT',
	'super'		=> 0,
	'debugging'	=> 1,
	'memo'		=> '',
	'email'		=> $_POST['m_email'],
	'setting'	=> serialize(array(
		'style'		=> 'default',
		'language'	=> 'zh-cn',
		'debug_pr'	=> 0,
		'debug_fb'	=> 0,
	)),
);
$managerid = $__db->insert("{$_POST['db_pre']}manager", $manager_info);
$oManager->cache_all(array($managerid));

## 获取远程配置信息
// License::system_update_notification();

echo <<<HTML
	<script type="text/javascript" language="javascript" charset="utf=8">
	<!--
		//document.getElementById('notice').innerHTML += '<iframe src="../app/autorun/lang.export.php" frameborder="0" style="width:960px; height:400px;"></iframe>';
		document.getElementById('action').innerHTML = '<input type="submit" value="安装完成" class="button" /><br />';
	//-->
	</script>
HTML
;
?>